#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 文件名：create_excel
# 当前用户：李峰
# 当前时间：2025/8/28 16:30
# 存储大模型生成的测试用例，写入excel中
# 外网ip:http://113.108.148.234:11185/
from flask import Blueprint, request, jsonify
import openpyxl
import os
import logging
from datetime import datetime
from pathlib import Path
from app.common.json_to_xmind import JsonToXmind
from config import datas_dir
# 注册蓝图
bp = Blueprint('create_excel', __name__,url_prefix=None)# 无法run的flask实例
# 举例访问/write_to_excel 若url_prefix=None则直接访问/write_to_excel即可
# url_prefix =/create,则需/create/write_to_excel访问
# url_prefix 的作用隔离相同url
# 设置日志
logger = logging.getLogger(__name__)
@bp.route('/write_to_excel', methods=['POST'])
def write_to_excel():
    # 验证请求头
    if 'Content-Type' not in request.headers:
        return jsonify({'error': '请求头无Content-Type'}), 400

    # 验证Content-Type
    if request.headers['Content-Type'] != 'application/json':
        return jsonify({'message': '请求头错误，请设为application/json'}), 400
    try:
        # 解析JSON数据
        request_data = request.get_json()
        data = request_data['data']
        # if not isinstance(request_data, dict) or 'data' not in request_data:
        #     return jsonify({'error': '入参要是json格式'}), 400

    except Exception as e:
        logger.error(f"数据验证过程中发生未知错误: {str(e)}")
        return jsonify({'message': '入参不符合要求'}),400

    if not isinstance(data, list) or not all(isinstance(row, list) for row in data):
        return jsonify({'message': 'data格式错误，请输入二维数组！'}), 400

    name = request_data['name']
    # 生成Excel文件名（使用当前时间戳）
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    base_name = f'{name}_测试用例_{timestamp}.xlsx'
    excel_filename = Path(datas_dir) / f"{base_name}"

    # 创建Excel工作簿和工作表
    wb = openpyxl.Workbook()
    ws = wb.active

    # 将数据写入Excel
    for row in data:
        ws.append(row)

    # 保存Excel文件
    wb.save(excel_filename)

    return jsonify({'message':f'{base_name}'}), 200

@bp.route('/llm_json_to_list',methods=['POST'])
def str_to_json():
    """
    把大模型的json输出转成list返回
    示例："``` json [{}]```"
    转成 [{}]
    :return:
    """
    # 验证请求头
    if 'Content-Type' not in request.headers:
        return jsonify({'error': '请求头无Content-Type'}), 400

    # 验证Content-Type
    if request.headers['Content-Type'] != 'application/json':
        return jsonify({'message': '请求头错误，请设为application/json'}), 400
    # —————————————用例数据结构化开始———————————————————————————
    try:
        # 解析JSON数据
        request_data = request.get_json(force=True)
        print(request_data)
        data_str = request_data.get('data')
        # print(f"直接获取{data_str}")

    except Exception as e:
        logger.error(f"数据验证过程中发生未知错误: {str(e)}")
        return jsonify({'message': '入参不符合要求'}),400
    list_data = []
    for row in data_str:
        # 将dict 转成list
        # print(f"row:{row}")
        j = []
        for i in range(0,len(row)):
            #逐一获取每个键值对值
            seventh_value = list(row.values())[i]
            j.append(seventh_value)
        list_data.append(j)
        # print(list_data)
    # —————————————用例数据结构化结束———————————————————————————
    name = request_data['name']
    # 将系统名转换成ms平台 所属模块

    # 生成Excel文件名（使用当前时间戳）
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    base_name = f'{name}_测试用例_{timestamp}.xlsx'
    excel_filename = Path(datas_dir) / f"{base_name}"

    # 创建Excel工作簿和工作表
    wb = openpyxl.Workbook()
    ws = wb.active

    # 将数据写入Excel
    for row in list_data:
        ws.append(row)

    # 保存Excel文件
    wb.save(excel_filename)
    # 开始写入xmind
    xmind_content = JsonToXmind(name,data_str,timestamp )
    xmind_name=xmind_content.json_to_xmind()
    return jsonify({r'message':f'{xmind_name}'}),200





